package com.suncaper.shop.controller;

import com.suncaper.shop.domain.Order;
import com.suncaper.shop.domain.OrderItem;
import com.suncaper.shop.domain.User;
import com.suncaper.shop.service.CartService;
import com.suncaper.shop.service.OrderService;
import com.suncaper.shop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class OrderController {
    @Autowired
    OrderService orderService;

    CartService cartService;

    UserService userService;

    @GetMapping("/order/create")
    public String goToOrder(HttpSession session, HttpServletRequest request) {
        orderService.save(session, request);

        return "redirect:/checkout";
    }


    @RequestMapping("/order")
    public String order(HttpSession session) {
        User userInfo = (User) session.getAttribute("userInfo");

        if (!orderService.orderList(session, userInfo.getId())) {

//            return "index";
        }

        return "order";
    }

    @RequestMapping("/orderdetails/{id}")
    public String order_deatils(@PathVariable("id") String oid, HttpSession session, Model model) {

        model.addAttribute("order", orderService.getOrder(oid, session));

        return "order_details";
    }

    @GetMapping("/checkout/{id}")
    public String goToCheckout(@PathVariable("id") String oid, HttpSession session) {

        Order order = orderService.getOrder(oid, session);
        session.setAttribute("order", order);

        return "checkout";
    }

    @PostMapping("/order/checkout")
    public String checkout(@RequestParam("oid") String oid, Order order, HttpSession session) {

        orderService.submitOrder(oid, order, session);
        session.removeAttribute("order");
        session.removeAttribute("cart");
        return "redirect:/order";
    }

    @GetMapping("/order/delete")
    public String delete(@RequestParam("oid") String oid) {
        orderService.deleteByOid(oid);
        return "redirect:/order";
    }
}
